package com.moogene.saad.gameplay.bullet;

import java.util.ArrayList;

import android.graphics.Point;
import android.graphics.Rect;

import com.moogene.android.engine.animlite.Animlite;
import com.moogene.android.engine.util.MooMath;
import com.moogene.saad.gameplay.attacter.Attacker;
import com.moogene.saad.gameplay.stages.DefendStage;

public class LaserPhysics extends Physics {
	private final static int SPEED = 15;

	private final int GAP = 10;
	private final int RADIUS = (GAP >> 1);
	private final int NUM_NODES = 8;
	private Rect nodes[];
	private int vX;
	private int vY;
	private ArrayList<Attacker> aBingos = new ArrayList<Attacker>(10);

	@Override
	public void shoot(Attacker attacker) {
		super.shoot(attacker);
		Animlite anim = bullet.getAttachedAnimlite();
		anim.getRotateAnim().setDegree(attacker.getX(), attacker.getY(),
				bullet.getX(), bullet.getY());
		int dis = MooMath.slowDistance(attacker.getX() - bullet.getX(),
				attacker.getY() - bullet.getY());
		vX = SPEED * (attacker.getX() - bullet.getX()) / dis;
		vY = SPEED * (attacker.getY() - bullet.getY()) / dis;
		nodes = new Rect[NUM_NODES];
		double angrad = Math.atan2(vY, vX);
		Point pAnchor = new Point();
		pAnchor.x = bullet.getX();
		pAnchor.y = bullet.getY();
		/* 138 is the anchor x of the animation */
		int x = bullet.getX()
				- bullet.getAttachedAnimlite().getAnchor().getAnchorX()
				+ RADIUS;
		int y = bullet.getY();
		Point pSrc = new Point();
		for (int i = 0; i < NUM_NODES; i++) {
			pSrc.x = x + i * GAP;
			pSrc.y = y;
			Point p = MooMath.getRotPoint(pSrc, pAnchor, angrad);
			nodes[i] = new Rect();
			nodes[i].left = p.x - RADIUS;
			nodes[i].right = p.x + RADIUS;
			nodes[i].top = p.y - RADIUS;
			nodes[i].bottom = p.y + RADIUS;
		}
	}

	@Override
	public ArrayList<Attacker> updateAndGetBingos() {
		aBingos.clear();
		bullet.move(vX, vY);
		ArrayList<Attacker> attackers = DefendStage.getInstance()
				.getBattleField().getAttackers();
		for (Attacker a : attackers) {
			Rect tarRect = a.getDstRect();
			for (Rect r : nodes) {
				r.offset(vX, vY);
				if (Rect.intersects(tarRect, r)) {
					aBingos.add(a);
				}
			}
		}
		return aBingos;
	}

}
